package com.my.feign.config.fallBack;

import com.baomidou.mybatisplus.extension.api.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.lang.Nullable;

import java.lang.reflect.Method;
import java.util.Objects;

/*自定义Feign熔断代理Fallback。*/
@Slf4j
public class XcloudFeignFallback<T> implements org.springframework.cglib.proxy.MethodInterceptor {

    private Class<T> targetType;
    private String targetName;
    private Throwable cause;

    public XcloudFeignFallback(Class<T> targetType, String targetName, Throwable cause) {
        this.targetType = targetType;
        this.targetName = targetName;
        this.cause = cause;
    }

    @Nullable
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
//        FeignException exception = (FeignException) cause;
//      String message =  exception.contentUTF8()
        String message = cause.getMessage();
        log.error("XcloudFeignFallback:[{}.{}] serviceId:[{}] message:[{}]",
                targetType.getName(), method.getName(),
                targetName,message);
        //  告警代码实现 ......
        return R.failed(message);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        XcloudFeignFallback<?> that = (XcloudFeignFallback<?>) o;
        return targetType.equals(that.targetType);
    }

    @Override
    public int hashCode() {
        return Objects.hash(targetType);
    }
}
